<?php
/**
 * 后台内容模型管理模型
 * CmsModel.php
 * ==============================================
 * 版权所有 2013-2014
 * ----------------------------------------------
 * 这不是一个自由软件，未经授权不许任何使用和传播。
 * ----------------------------------------------
 * 
 * @package xcs
 * @author Huangdaohai <huangdaohai.2007@163.com>
 * @version $Id$
 * @access public
 */
class CmsModel extends BaseModel
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return AdminCmsModel the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{cms_model}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('site_id, model_name, table_name, default_style, category_template, list_template, show_template', 'required'),
			array('site_id, disable, sort, createtime, updatetime', 'numerical', 'integerOnly'=>true),
			array('model_name, table_name, default_style, category_template, list_template, show_template', 'length', 'max'=>30),
			array('description', 'length', 'max'=>100),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('model_id, site_id, model_name, description, table_name, setting, default_style, category_template, list_template, show_template, disable, sort, createtime, updatetime', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}
    /**
	 * 获取菜单列表
	 *
	 * @param array $params
	 * @return array 数据数组和分页对象
	 */
	public function getList($params){
		$iPage = (isset($params['page']) && !empty($params['page'])) ? $params['page'] : 1;
		$iPagesize = (isset($params['pagesize']) && !empty($params['pagesize'])) ? $params['pagesize'] : Yii::app()->params->pageSize;

		$criteria = new CDbCriteria();
        $criteria->order = 'createtime DESC' ;//排序条件 		
		$iCcount = self::model()->count($criteria);
		$oPages = new CPagination($iCcount);
		$oPages->pageSize = $iPagesize;
		$oPages->setCurrentPage($iPage-1);
		$oPages->applyLimit($criteria);
		$oResult = self::model()->findAll($criteria);

		$aList = array();
		if(!empty($oResult)){
			foreach ($oResult as $iKey => $aVal){
				$aList[$iKey]['model_id'] = $aVal->model_id;
                $aList[$iKey]['site_id'] = $aVal->site_id;
                $aList[$iKey]['model_name'] = $aVal->model_name;
                $aList[$iKey]['description'] = $aVal->description;
                $aList[$iKey]['table_name'] = $aVal->table_name;
                $aList[$iKey]['setting'] = $aVal->setting;
                $aList[$iKey]['default_style'] = $aVal->default_style;
				$aList[$iKey]['category_template'] = $aVal->category_template;
                $aList[$iKey]['list_template'] = $aVal->list_template;
                $aList[$iKey]['show_template'] = $aVal->show_template;
                $aList[$iKey]['disable'] = $aVal->disable;
                $aList[$iKey]['sort'] = $aVal->sort;
                $aList[$iKey]['createtime'] = $aVal->createtime;
                $aList[$iKey]['updatetime'] = $aVal->updatetime;
				//$list[$key]['tabletree'] = $this->getTreeTable($fidvalue."_".$value['area_id']);
			}
		}
		$listResult['list'] = $aList;
		$listResult['pages'] = $oPages;

		return $listResult;
	}
    /**
     * CmsModel::getAllModelList()
     * 
     * @param array $default 默认选择的内容
     * @return array $aReturn 所有模型的一维数组
     */
    public static function getAllModelList($default=array()){
        !$default && $aReturn = array(''=>'请选择');
        $aAllData = self::model()->getList(array('pagesize'=>100));
        if( $aAllData['list'] ){
            foreach( $aAllData['list'] as $iKey=>$aVal ){
                $aReturn[$aVal['model_id']] = $aVal['model_name'];
            }
        }
        return $aReturn;
    }
    /**
     * CmsModel::getOne()
     * 
     * @param mixed $iModelId
     * @return
     */
    public function getOne($iModelId){
        $oModel = $this->findByPk($iModelId);
        return $oModel->attributes;
    }
    /**
     * CmsModel::saveData() 保存数据
     * 
     * @param array $attributes 属性数组
     * @param bool $isverify 是否验证
     * @return mix 保存成功返回 主键ID  失败返回错误数组
     */
    public function saveData($attributes ,$isverify=true){
        $this->attributes=$attributes;
        if( $isverify ){
            if( $this->save() ){
                //保存成功             
                return $this->model_id;
            } else {
                return $this->errors;
            }
        } else {
            $this->save(false);
            return $this->model_id;
        }
        
    }
    public function verifyFieldTableName($tablename){
        $oField = self::model()->find('table_name="'.$tablename.'"');
        if( $oField && $oField->table_name==$tablename ){
            return true;
        } else {
            return false;
        }
    }
    /**
     * CmsModel::executeSQL() 执行SQL语句
     * 
     * @param string $sql 需要执行的SQL
     * @return bool 执行成功与否
     */
    public function executeSQL($sql) {
		$sqls = $this->splitSQL($sql);
		if(is_array($sqls)) {
			foreach($sqls as $sql) {
				if(trim($sql) != '') {
                    Yii::app()->db->createCommand($sql)->execute();
				}
			}
		} else {
            Yii::app()->db->createCommand($sqls)->execute();
		}
		return true;
	}
	/**
	 * CmsModel::splitSQL() 处理SQL
	 * 
	 * @param string $sql 需要处理的SQL
	 * @return string 
	 */
	public function splitSQL($sql) {
		if( Yii::app()->admincommon->getMysqlVersion() > '4.1' && Yii::app()->db->charset) {
			$sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=".Yii::app()->db->charset,$sql);
		}
		if(Yii::app()->db->tablePrefix != "x_") $sql = str_replace("x_", Yii::app()->db->tablePrefix, $sql);
		$sql = str_replace("\r", "\n", $sql);
		$ret = array();
		$num = 0;
		$queriesarray = explode(";\n", trim($sql));
		unset($sql);
		foreach($queriesarray as $query) {
			$ret[$num] = '';
			$queries = explode("\n", trim($query));
			$queries = array_filter($queries);
			foreach($queries as $query) {
				$str1 = substr($query, 0, 1);
				if($str1 != '#' && $str1 != '-') $ret[$num] .= $query;
			}
			$num++;
		}
		return $ret;
	}
    /**
     * CmsModel::deleteData()
     * 
     * @param mixed $oModel
     * @return
     */
    public function deleteData($oModel){
        $bReslut = true;
        //获取模型ID
        $iModel = $oModel->model_id;
        //删除对应模型字段
        
        if( !CmsModelField::model()->deleteAll('model_id='.$iModel) ) $bReslut = false;
        //删除对应表
        $sTableName = Yii::app()->db->tablePrefix .'cms_'.$oModel->table_name;
        if( Yii::app()->db->createCommand("DROP TABLE $sTableName")->execute()!=0 ) $bReslut = false;
        if( !$oModel->delete() ) $bReslut = false;
        return $bReslut;
    }
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'model_id' => 'modelid',
			'site_id' => '站点ID',
			'model_name' => '模型名称',
			'description' => '描述',
			'table_name' => '数据表',
			'setting' => '设置',
			'default_style' => '默认风格',
			'category_template' => '首页模板',
			'list_template' => '列表模板',
			'show_template' => '详细模板',
			'disable' => '禁用',
			'sort' => '排序',
			'createtime' => '创建时间',
			'updatetime' => '更新时间'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('model_id',$this->model_id);
		$criteria->compare('site_id',$this->site_id);
		$criteria->compare('model_name',$this->model_name,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('table_name',$this->table_name,true);
		$criteria->compare('setting',$this->setting,true);
		$criteria->compare('default_style',$this->default_style,true);
		$criteria->compare('category_template',$this->category_template,true);
		$criteria->compare('list_template',$this->list_template,true);
		$criteria->compare('show_template',$this->show_template,true);
		$criteria->compare('disable',$this->disable);
		$criteria->compare('sort',$this->sort);
		$criteria->compare('createtime',$this->createtime);
		$criteria->compare('updatetime',$this->updatetime);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}